20. Exercise: onSaveInstanceState

L4 39 Onsaved Instant State HSSC 1 V2

Now it’s your turn to complete this exercise yourself.

In this exercise you'll make sure that your data is saved and restored, even if your app is shut down in the background.

**1. Override onSaveInstanceState and onRestoreInstanceState: **

You can use the keyboard shortcut Ctrl + O to do this. For onSaveInstanceState, you can use the version that has one parameter, the Bundle.

**2. Save the data in onSaveInstanceState: **

You should save the revenue, dessertsSold and dessertTimer.secondsCount in the state Bundle. Here's an example of saving the revenue:

outState.putInt(KEY_REVENUE, revenue)

Note that KEY_REVENUE is a string constant.

**3. Retrieve and use the data in onCreate if you're restarting to Activity: **

Check that the Bundle is not null in onCreate, and then retrieve and use the data. For example:

if (savedInstanceState != null) {
        revenue = savedInstanceState.getInt(KEY_REVENUE, 0)
     }

If you want to start at this step, you can download this exercise code from: Step.05-Exercise-Implement-onSaveInstanceState.

You will find plenty of //TODO comments to help you complete this exercise, and if you get stuck, go back and watch the video again.

Once you’re done, you can check your solution against the solution we’ve provided here Step.05-Solution-Implement-onSaveInstanceState or using this git diff

Task Description:

Check the steps below as you implement them to complete this exercise.

Task List:

Task Feedback:

Great job!

Solution: Step.05-Solution-Implement-onSaveInstanceState or using this git diff